package com.szy.news;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.szy.news.model.Category;
import com.szy.news.service.SyncHttp;
import com.szy.news.util.DensityUtil;
import com.szy.news.util.StringUtil;

/**
 *@author coolszy
 *@date 2012-2-7
 *@blog http://blog.92coding.com
 *
 */
public class MainActivity extends Activity
{
	private final int COLUMNWIDTHPX = 56;
	private final int FLINGVELOCITYPX =800; //滚动距离
	
	private String categoryName;//新闻分类名称
	private int cid;//新闻分类编号
	private int columnWidthDip;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		columnWidthDip = DensityUtil.px2dip(this, COLUMNWIDTHPX);
		
		Resources res = getResources();
		//获取新闻类型
		String[] categoryArray = res.getStringArray(R.array.categories);
		final ArrayList<HashMap<String, Category>> categories = new ArrayList<HashMap<String, Category>>();
		//构造新闻分类
		for (String category : categoryArray)
		{
			String[] temp = category.split("[|]");
			if (temp.length==2)
			{
				int cid = StringUtil.String2Int(temp[0]);
				String title = temp[1];
				Category type = new Category(cid, title);
				HashMap<String, Category> hashMap = new HashMap<String, Category>();
				hashMap.put("category_title", type);
				categories.add(hashMap);
			}
		}
		//获取初始界面的新闻分类名称和编号
		categoryName = categories.get(0).get("category_title").getTitle();
		cid = categories.get(0).get("category_title").getCid();
		
		GridView gridView = new GridView(this);
		gridView.setColumnWidth(columnWidthDip);// 设置每个分页按钮的宽度
		gridView.setNumColumns(GridView.AUTO_FIT);// 分页按钮数量自动设置
		gridView.setGravity(Gravity.CENTER);//设置对其方式
		
		int width = columnWidthDip * categories.size();
		LayoutParams params = new LayoutParams(width, LayoutParams.FILL_PARENT);
		gridView.setLayoutParams(params);
		SimpleAdapter adapter = new SimpleAdapter(this, categories,// 数据来源
				R.layout.category_title,// XML实现
				new String[]
					{ "category_title" },// 动态数组与ImageItem对应的子项
				new int[]
					{ R.id.category_title });
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridView.setAdapter(adapter);
		LinearLayout categoryList = (LinearLayout) findViewById(R.id.category_list);
		categoryList.addView(gridView);
		
		gridView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				TextView categoryTitle;
				for (int i = 0; i < parent.getChildCount(); i++)
				{
					categoryTitle = (TextView) (parent.getChildAt(i));
					categoryTitle.setBackgroundDrawable(null);
					categoryTitle.setTextColor(0xFFADB2AD);
				}
				categoryTitle = (TextView) (parent.getChildAt(position));
				categoryTitle.setBackgroundResource(R.drawable.image_categorybar_item_selected_background);
				categoryTitle.setTextColor(0xFFFFFFFF);
				categoryName = categories.get(position).get("category_title").getTitle();
				cid = categories.get(position).get("category_title").getCid();
			}
		});
		//修改第一个item状态
//		TextView categoryTitle = (TextView) gridView.getAdapter().getView(0, null, null);
//		categoryTitle.setBackgroundResource(R.drawable.image_categorybar_item_selected_background);
//		categoryTitle.setTextColor(0xFFFFFFFF);
		
		// 箭头
		final HorizontalScrollView column_scrollview = (HorizontalScrollView) findViewById(R.id.category_scrollview);
		Button categoryArrowRight = (Button) findViewById(R.id.category_arrow_right);
		categoryArrowRight.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				column_scrollview.fling(DensityUtil.px2dip(MainActivity.this, FLINGVELOCITYPX));
			}
		});
		
		//显示首页新闻列表
//		HashMap<String, Object> hashMap = new HashMap<String, Object>();
//		hashMap.put("textViewListItemTitle", "Android一些关于分辨率和布局的设置");
//		hashMap.put("textViewListItemSummary", "Android手机屏幕大小不一，有480x320, 640x360, 800x480.怎样才能让...");
//		hashMap.put("textViewListItemFrom", "来源：腾讯网");
//		hashMap.put("textViewListItemUpdateTime", "2012-11-11 11:11:11");
//		HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
//		hashMap2.put("textViewListItemTitle", "菲律宾南部洪灾已造成近200人死亡 数百人失踪");
//		hashMap2.put("textViewListItemSummary", "带风暴“天鹰”在菲律宾南部棉兰老岛造成的洪灾灾情持续扩大，最新消息称，当地已有近200人死亡。");
//		hashMap2.put("textViewListItemFrom", "来源：人民网");
//		hashMap2.put("textViewListItemUpdateTime", "2012-11-11 11:11:11");
		final ArrayList<HashMap<String, Object>> newsList = new ArrayList<HashMap<String, Object>>();
		getSpecifyCategoryNews(cid,newsList);
//		for (int i = 0; i < 5; i++)
//		{
//			newsList.add(hashMap);
//			newsList.add(hashMap2);
//		}
		SimpleAdapter adapter2 = new SimpleAdapter(this, newsList, R.layout.newslist_item, new String[]
			{ "title", "digest", "source", "ptime" }, new int[]
			{ R.id.textViewListItemTitle, R.id.textViewListItemSummary, R.id.textViewListItemFrom, R.id.textViewListItemUpdateTime });
		ListView lv = (ListView) findViewById(R.id.news_list);
		lv.setAdapter(adapter2);
		lv.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				Intent intent = new Intent(MainActivity.this,NewsDetailsActivity.class);
				intent.putExtra("newsList", newsList);
				intent.putExtra("position", position);
				intent.putExtra("categoryName", categoryName);
				startActivity(intent);
			}
		});
	}
	
	private String getSpecifyCategoryNews(int cid,ArrayList<HashMap<String, Object>> newsList)
	{
		String url = "http://10.0.2.2:8080/web/getSpecifyCategoryNews";
		String params = "startnid=0&count=10&cid="+cid;
		SyncHttp syncHttp = new SyncHttp();
		try
		{
			String retString = syncHttp.httpGet(url, params);
			JSONObject jsonObject = new JSONObject(retString);
			int errcode = jsonObject.getInt("errcode");
			if (0==errcode)
			{
				JSONObject dataObject = jsonObject.getJSONObject("data");
				int totalnum = dataObject.getInt("totalnum");
				if (totalnum>0)
				{
					JSONArray newslist = dataObject.getJSONArray("newslist");
					for(int i=0;i<newslist.length();i++)
					{
						JSONObject newsObject = (JSONObject)newslist.opt(i); 
						HashMap<String, Object> hashMap = new HashMap<String, Object>();
						hashMap.put("nid", newsObject.getInt("nid"));
						hashMap.put("title", newsObject.getString("title"));
						hashMap.put("digest", newsObject.getString("digest"));
						hashMap.put("source", newsObject.getString("source"));
						hashMap.put("ptime", newsObject.getString("ptime"));
						hashMap.put("commentcount", newsObject.getInt("commentcount"));
						newsList.add(hashMap);
					}
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
}